﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Read.API.Command.UserCommand;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace B.S.BaseData.Read.API.CommandHandler.UserHandler
{
    public class LoginUserHandler : IRequestHandler<LoginUserCommand, APIResult<User>>
    {
        private readonly IBaseRepository<User> userRep;
        private readonly IMapper mapper;
        private readonly IBaseRepository<UserRole> urRep;
        private readonly ILogger<LoginUserCommand> logger;

        public LoginUserHandler(IBaseRepository<User> userRep,IMapper mapper,IBaseRepository<UserRole> urRep, ILogger<LoginUserCommand> logger)
        {
            this.userRep = userRep;
            this.mapper = mapper;
            this.urRep = urRep;
            this.logger = logger;
        }
        public Task<APIResult<User>> Handle(LoginUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<User> result = new APIResult<User>();
            
            var user = userRep.GetAll().Where(x=>x.Name==request.Name).FirstOrDefault();
         
            if (user == null) 
            {
                result.Code=APIEnum.用户名不存在;
                result.Msg=APIEnum.用户名不存在.ToString();
              
            }
            else
            {
                var roleId = urRep.GetAll().Where(x => x.UserId == user.UserId).FirstOrDefault().RoleId.ToString();
                if (user.Pass!=request.Pass)
                {
                    result.Code = APIEnum.用户名和密码不匹配;
                    result.Msg = APIEnum.用户名和密码不匹配.ToString();
                }
                else 
                {
                    result.Code = APIEnum.登陆成功;
                    result.Msg = CreateTokenString(user.UserId.ToString(), roleId);
                    result.Data = user;
                    logger.LogInformation(user.Name+" 登陆成功！");
                   
                }
            }

            return Task.FromResult(result);
        }

        private string CreateTokenString(string uid,string rid)
        {
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,uid),
                new Claim(ClaimTypes.Role,rid)
            };
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }




    }





}
